﻿/**************************************************************
 *
 * 唯一标识：f717e1b0-fee2-4ef7-bcea-04966473fa05
 * 命名空间：Xunit.Sgr
 * 创建时间：2024/7/21 19:31:41
 * 机器名称：DESKTOP-HJ4OAG9
 * 创建者：CocoYuan
 * 电子邮箱：fengqinhua2016@163.com
 * 描述：
 *
 **************************************************************/

using Microsoft.AspNetCore.Hosting;
using Sgr.Tests;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Sgr.MediatR.Behaviors;
using Sgr.Utilities;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Sgr.UPMS.Application.Commands.Users;
using Microsoft.AspNetCore.Mvc.Testing;

namespace Xunit.Sgr
{
    public class SgrAppTestFixture : SgrBaseTestFixture
    {
        public SgrAppTestFixture() : base()
        {
        }

        protected override void InitTestData()
        {
            AsyncHelper.RunSync(() => { return TestHelper.InitData(base.ServiceProvider); });
        }

        protected override void ConfigureWebHost(IWebHostBuilder builder)
        {
            base.ConfigureWebHost(builder);

            builder.ConfigureAppConfiguration(c =>
            {
                var directory = Path.GetDirectoryName(typeof(SgrAppTestFixture).Assembly.Location)!;
                c.AddJsonFile(Path.Combine(directory, "appsettings.json"), optional: false);
            });

            builder.ConfigureServices((context, services) =>
            {
                services.AddDbContexts(context.Configuration);
                services.AddSgrWeb(context.Configuration, context.HostingEnvironment);
                services.AddTransient<IHttpContextAccessor, HttpContextAccessor>();

                services.AddMediatR(cfg =>
                {
                    cfg.RegisterServicesFromAssemblyContaining(typeof(CreateUserCommand));
#if DEBUG
                    cfg.AddOpenBehavior(typeof(LoggingBehavior<,>));
#endif
                    cfg.AddOpenBehavior(typeof(ValidatorBehavior<,>));
                    cfg.AddOpenBehavior(typeof(TransactionBehavior<,>));
                });

                services.AddControllers().AddJsonOptions(options => { JsonHelper.UpdateJsonSerializerOptions(options.JsonSerializerOptions); });
                services.AddEndpointsApiExplorer();
                services.AddSgrAuthentication(context.Configuration, true);
            });

            builder.Configure(app =>
            {
                app.UseSgrWeb();
                app.UseHttpsRedirection();
                app.UseAuthentication();
                app.UseAuthorization();
                app.UseStaticFiles();
                app.UseRouting();
                app.UseEndpoints(endpoints =>
                {
                    endpoints.MapControllers();
                });
            });
        }
    }
}